package org.exhaust.framework.net.test.protocol.server.udp.app;

import lombok.extern.slf4j.Slf4j;
import org.exhaust.framework.net.common.protocol.BaseUdpFrame;
import org.exhaust.framework.net.common.protocol.ChannelEventDispatcher;
import org.exhaust.framework.net.common.protocol.decoder.ByteBufDecoderHelper;
import org.exhaust.framework.net.common.protocol.decoder.udp.UdpDecoder;
import org.exhaust.framework.net.common.protocol.encoder.UdpFrameEncoder;
import org.exhaust.framework.net.common.protocol.handler.BusinessDataHandler;
import org.exhaust.framework.net.server.udp.BaseUdpServer;
import org.exhaust.framework.net.server.udp.UdpServerProperty;
import org.exhaust.framework.net.test.protocol.server.udp.decoder.ClientDemoMsgDecoderHelper;
import org.exhaust.framework.net.test.protocol.server.udp.handler.ClientMsgBusinessDataHandler;

import java.util.concurrent.CountDownLatch;

@Slf4j
public class UdpServerApplication {

    public static void main(String[] args) throws Exception {

//        ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.directBuffer();
//        byteBuf.writeShort(HelloMsg.MSG_TYPE);
//        byte[] data="hello，bigfish！".getBytes(StandardCharsets.UTF_8);
//        byteBuf.writeInt(data.length);
//        byteBuf.writeBytes(data);
//
//        System.out.println(ByteBufUtil.hexDump(byteBuf));


        ByteBufDecoderHelper decoderHelper = new ClientDemoMsgDecoderHelper();

        BusinessDataHandler<BaseUdpFrame> handler = new ClientMsgBusinessDataHandler();

        UdpDecoder udpDecoder = new UdpDecoder(decoderHelper, handler);

        UdpFrameEncoder encoder = new UdpFrameEncoder();

        ChannelEventDispatcher dispatcher = new ChannelEventDispatcher();

        UdpServerProperty serverProperty = new UdpServerProperty();
        serverProperty.setPort(13000);
        serverProperty.setIoThreadNum(2);
        BaseUdpServer server = new BaseUdpServer(() -> {
            return new UdpDecoder(decoderHelper, handler);
        }, encoder, dispatcher, serverProperty);
        new Thread(() -> {
            try {
                server.start();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }).start();

        CountDownLatch latch = new CountDownLatch(1);
        latch.await();
    }
}
